package com.jia.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.jia.pojo.User;
import com.jia.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
public class UserController {

    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
        // jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("杜佳佳",16,"男");
        String str = mapper.writeValueAsString(user);

        return str;
    }

    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {

        List<User> userList = new ArrayList<User>();
        //创建一个对象
        User user1 = new User("杜佳佳 1",16,"男");
        User user2 = new User("杜佳佳 2",16,"男");
        User user3 = new User("杜佳佳 3",16,"男");
        User user4 = new User("杜佳佳 4",16,"男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        
        return JsonUtils.getJson(userList);
    }

    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {

        // 1.
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // sdf.format(date)
        // jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        // 不使用时间戳的方式
        mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(sdf);
        //创建一个对象
        Date date = new Date();

        return mapper.writeValueAsString(date);
    }

    @RequestMapping("/j4")
    public String json4(){

        Date date = new Date();

        return JsonUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");
    }

    @RequestMapping("/j5")
    public String json5(){

        List<User> userList = new ArrayList<User>();
        //创建一个对象
        User user1 = new User("杜佳佳 1",16,"男");
        User user2 = new User("杜佳佳 2",16,"男");
        User user3 = new User("杜佳佳 3",16,"男");
        User user4 = new User("杜佳佳 4",16,"男");

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        String jsonString = JSON.toJSONString(userList);
        return jsonString;
    }


}
